package ru.arriah.servicedesk.help;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public final class DbUtils {

   /**
    * Close a Connection, avoid closing if null
    * @param conn
    * @throws SQLException
    */
   public static void close(
      Connection conn
   ) throws SQLException {
      if (conn != null) {
         conn.close();
      }
   }

   
   public static void close(
      ResultSet rs
   ) throws SQLException {
      if (rs != null) {
         rs.close();
      }
   }

   
   public static void close(
      Statement stmt
   ) throws SQLException {
      if (stmt != null) {
         stmt.close();
      }
   }

   
   public static void closeQuietly(Connection conn) {
      try {
         close(conn);
      } catch (SQLException e) {
         e.printStackTrace();
      }
   }

   
   public static void closeQuietly(
      Connection conn, 
      Statement stmt, 
      ResultSet rs
   ) {
      try {
         closeQuietly(rs);
      } finally {
         try {
            closeQuietly(stmt);
         } finally {
            closeQuietly(conn);
         }
      }

   }
   
   
   public static void closeQuietly(
      Connection conn, 
      Statement stmt
   ) {
      try {
         closeQuietly(stmt);
      } finally {
         closeQuietly(conn);
      }
   }

   
   public static void closeQuietly(
      ResultSet rs
   ) {
      try {
         close(rs);
      } catch (SQLException e) {
         e.printStackTrace();
      }
   }

   
   public static void closeQuietly(Statement stmt) {
      try {
         close(stmt);
      } catch (SQLException e) {
         e.printStackTrace();
      }
   }

   
   public static void commitAndClose(
      Connection conn
   ) throws SQLException {
      if (conn != null) {
         try {
            conn.commit();
         } finally {
            conn.close();
         }
      }
   }

   
   public static void commitAndCloseQuietly(
      Connection conn
   ) {
      try {
         commitAndClose(conn);
      } catch (SQLException e) {
         e.printStackTrace();
      }
   }

}